package com.gopay.bis.bocom.ebank.operation;

import com.bankcomm.netpay.Config;
import com.gopay.bis.common.util.BankLogUtils;
import com.gopay.common.constants.proccode.ProcCodeConstants;
import com.gopay.common.domain.bank.BaseMessage;
import com.gopay.common.domain.bank.bocom.ebank.pay.BocomB2cMessage;
import com.gopay.common.exception.GopayException;
import com.gopay.remote.bank.ICertHelper;

public class BocomB2cCertHelper implements ICertHelper{
    private String filePath;

    public String sign(BaseMessage message) throws GopayException {
        try {
            // B2C
            BocomB2cMessage messageB2c = (BocomB2cMessage) message;
            BankLogUtils.printB2CSignPlainLog(messageB2c);
            String configID = "b2cpay";
            // 借贷分离判断
            if (!messageB2c.isSupportCredit()) {
                configID = "debitb2cpay";
            }
            
            Config.loadConfig(filePath);
            String signMsg = Config.detachedSign(configID,messageB2c.getPlainMessage());
            BankLogUtils.printB2CSignSignatureLog(messageB2c, signMsg);
            return signMsg;
        } catch (Exception e) {
            BankLogUtils.printB2CSignExceptionLog(message, e);
            throw new GopayException(ProcCodeConstants.PROC_CODE_100E6029);
        }
    }

    public Object verify(BaseMessage message) throws GopayException {
        try {
            BocomB2cMessage bocomB2cMessage = (BocomB2cMessage) message;
            boolean flag = true;
            
            String configID = "b2cpay";
            String merId = bocomB2cMessage.getPlainMessage().substring(0,
                    bocomB2cMessage.getPlainMessage().indexOf("|"));
            // 借贷分离判断
            if ("301110089999542".equals(merId)) {
                configID = "debitb2cpay";
            }
            
            Config.loadConfig(filePath);
            String verifyRes = Config.detachedVerify(configID,bocomB2cMessage.getPlainMessage(), bocomB2cMessage.getSignMessage());
            if("".equals(verifyRes)) {
                flag = false;
            }
            
            BankLogUtils.printB2CVerifyPlainLog(bocomB2cMessage);
            BankLogUtils.printB2CVerifySignatureLog(bocomB2cMessage, bocomB2cMessage.getSignMessage());
            BankLogUtils.printB2CVerifyResultLog(bocomB2cMessage, flag);
            return flag;
        } catch (Exception e) {
            BankLogUtils.printB2CSignExceptionLog(message, e);
            throw new GopayException(ProcCodeConstants.PROC_CODE_100E6031);
        }    
    }

    public String getFilePath() {
        return filePath;
    }

    public void setFilePath(String filePath) {
        this.filePath = filePath;
    }
}
